package com.harboursoftware.xstorage.ac;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

import com.harboursoftware.xstorage.model.XUser;

/**
 * 表示群组的授权对象。
 * 
 * @author Simon Leung
 * @since 0.1
 */
public class GroupGrantee implements Grantee {
    private final static String ALL_USERS_URI = "http://acs.amazonaws.com/groups/global/AllUsers";
    private final static String AUTHENTICATED_USERS_URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";
	/** all users */
	public final static GroupGrantee ALL_USERS = new GroupGrantee(ALL_USERS_URI, Integer.MAX_VALUE);
	/** authenticated users */
	public final static GroupGrantee AUTHENTICATED_USERS = new GroupGrantee(AUTHENTICATED_USERS_URI, 8);
	private String uri;
	private int scope;

	private GroupGrantee(String uri, int scope) {
		this.uri = uri;
		this.scope = scope;
	}
	
	public static GroupGrantee createInstanceByUri(String uri) {
	    if(ALL_USERS_URI.equals(uri)) {
            return GroupGrantee.ALL_USERS;
        } else if(AUTHENTICATED_USERS_URI.equals(uri)) {
            return GroupGrantee.AUTHENTICATED_USERS;
        } else {
            throw new IllegalArgumentException("");
          //TODO:log
        }
	}

	public boolean contains(XUser user) {
		if (this == ALL_USERS) { // anonymous
			return true;
		}
		// this == AuthenticatedUsers
		if (user != null && user.getId() != null) {
			return true;
		}
		return false;
	}

	public String toXML() {
		if (this == ALL_USERS) {
			return "<Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"Group\"><URI>http://acs.amazonaws.com/groups/global/AllUsers</URI></Grantee>";
		} else { // this == AUTHENTICATED_USERS
			return "<Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"Group\"><URI>http://acs.amazonaws.com/groups/global/AuthenticatedUsers</URI></Grantee>";
		}
	}

	public int getScope() {
		return scope;
	}

	public String getUri() {
		return uri;
	}

	public void setUri(String uri) {
		this.uri = uri;
	}
	
	
    @Override
    public boolean equals(Object obj) {
        //TODO: 删除该方法
        return EqualsBuilder.reflectionEquals(this, obj);
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

	@Override
	public String toString() {
		return "GroupGrantee [" + uri + "]";
	}
}
